package com.mxx.common.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Author itzgyw
 * @Date 2020-02-20
 * @Time 20:45
 * @Description:
 */
public class SignUtil {

    public static String toMD5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法！");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);
        for (; md5code.length() < 32; ) {
            md5code = "0" + md5code;
        }
        return md5code;
    }


    public static String byteToHex(byte[] buf) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < buf.length; ++i) {
            String hex = Integer.toHexString(buf[i] & 255);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }

            sb.append(hex);
        }

        return sb.toString();
    }

    public static byte[] hexToByte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        } else {
            byte[] result = new byte[hexStr.length() >> 1];

            for (int i = 0; i < hexStr.length() >> 1; ++i) {
                int high = Integer.parseInt(hexStr.substring(i << 1, (i << 1) + 1), 16);
                int low = Integer.parseInt(hexStr.substring((i << 1) + 1, i + 1 << 1), 16);
                result[i] = (byte) ((high << 4) + low);
            }

            return result;
        }
    }
}
